import React, { Component } from 'react'
import { Form, Input, Row, Col, Button , Select, Cascader, message } from 'antd';
import PhotoUpload from '../PhotoUpload/PhotoUpload'
const FormItem = Form.Item;
const Option = Select.Option;

class NumberInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: props.value
        }
    }

    componentWillReceiveProps (nextProps) {
        if(nextProps.value && nextProps.value !== this.props.value) {
            this.state = {
                value: nextProps.value
            }
        }
    }

    handleOnChange = (e) => {
        const { value } = e.target;
        //const reg = /^(0|[1-9][0-9]*)(\.[0-9]{0,2})?$/;
        const reg = /^(0|[1-9]+[0-9]*)$/;
        let flag = true;
        if (this.props.length && value.split('.')[0].length > this.props.length) {
            flag = false;
        }
        if ((!isNaN(value) && reg.test(value) && flag) || value === '' ) {
            this.handleValueSet(value);
        }
    }

    handleOnBlur = (e) => {
        const { value } = e.target;
        if(value.charAt(value.length - 1) === '.') {
            this.handleValueSet(value.substring(0,value.length-1))
        }
    }

    handleValueSet = (value) => {
        const { onChange } = this.props;
        this.setState({value: value});
        if (onChange) {
            onChange(value);
        }
    }

    render () {
        return <Input size='large'
                      value={this.state.value}
                      onChange={this.handleOnChange}
                      onBlur={this.handleOnBlur}
                      disabled={this.props.disabled}/>
    }
}

class ItemModifyForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            fileList: [],
            fileList2: [],
            disabled: false
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.defaultData !== nextProps.defaultData) {
            this.setState({
                fileList: [{
                    uid: -1,
                    name: 'image1.png',
                    status: 'done',
                    url: nextProps.defaultData.imageUrl1,
                }],
                fileList2: [{
                    uid: -1,
                    name: 'image2.png',
                    status: 'done',
                    url: nextProps.defaultData.imageUrl2,
                }],
                disabled: nextProps.defaultData.status === -1 ? true : false
            })
        }
    }

    handleSubmit = (e) => {
        e.preventDefault()
        const { defaultData, form } = this.props;
        let values = this.props.form.getFieldsValue();
        if(defaultData.status === -1) {
            form.validateFieldsAndScroll(['newStatus'],(err) => {
                if (!err) {
                    this.props.onSubmit({
                     oldStatus: defaultData.status,
                     newStatus: values.newStatus
                     });
                }
            })
            return;
        }
        values.oldStatus = defaultData.status;
        values.newStatus = values.newStatus ||　defaultData.status + '';
        if (values.image) {
            values.imageKey1 = values.image[0].imageKey1;
            values.imageKey2 = values.image[0].imageKey2;
            delete values.image;
        }
        if(values.categoryId) {
            values.categoryId = values.categoryId[values.categoryId.length -1] || "0";
        }
        if(values.newStatus === "0"){
            this.props.onSubmit(values);
        } else {
            form.validateFieldsAndScroll((err) => {
                if (!err) {
                    this.props.onSubmit(values);
                }
            })
        }
    }

    handleCancel = () => {
        this.props.onCancel();
    }

    handlePhotoUpload = (fileList, url2) => {
        if(fileList[0].response && fileList[0].response.status !== 200) {
            message.error(fileList[0].response.err);
            this.props.form.setFieldsValue({image: ''})
            this.setState({
                fileList: [],
                fileList2: []
            })
            return false;
        }
        this.props.form.setFieldsValue({image: fileList});
        this.setState({
            fileList: fileList,
            fileList2: [{
                uid: -1,
                name: 'image2.png',
                status: 'done',
                url: url2,
            }]
        })
    }

    handlePhotoRemove = () => {
        this.props.form.setFieldsValue({image: ''})
        this.setState({
            fileList: [],
            fileList2: []
        })
    }

    newStatusConfirm = (rule, value, callback) => {
        const { defaultData } = this.props;
        if (value && defaultData.status === -1 && value === '-1') {
            callback('必须修改商品状态');
        } else {
            callback();
        }
    }

    handleStatusSelect = (e) => {
        if (this.props.defaultData.status !== -1) {
            this.setState({
                disabled: e === "-1" ? true : false
            })
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { defaultData, loading, categoryList } = this.props;
        const { disabled } = this.state; //defaultData.status === -1 ? true : false;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 3 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 19 },
            },
        };
        const formItemLayoutInline2 = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const formItemLayoutInline4 = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 12 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
            },
        };
        return (
            <Form onSubmit={this.handleSubmit} style={{maxWidth: 1000}}>
                <FormItem
                    {...formItemLayout}
                    label="商品编码"
                    >
                    <span>{defaultData.itemCode || ''}</span>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="p4类别"
                    >
                    <span>{defaultData.p4CategoryNames || ''}</span>
                </FormItem>
                <Row>
                    <Col span={12}>
                        <FormItem
                            {...formItemLayoutInline2}
                            label="商品状态"
                            >
                            {getFieldDecorator('newStatus', {
                                rules: [{
                                    validator: this.newStatusConfirm,
                                }, {
                                    required: true, message: '必须选择商品状态',
                                }],
                                initialValue: defaultData.status === undefined ? '' :  defaultData.status + ''
                            })(
                                <Select placeholder="请输选择商品状态"
                                        onSelect={this.handleStatusSelect}>
                                    <Option value="0" disabled={defaultData.status !== 0}>未启用</Option>
                                    <Option value="1">启用</Option>
                                    <Option value="-1" disabled={defaultData.status === 0}>禁用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem
                            {...formItemLayoutInline2}
                            label="商品分类"
                            >
                            {getFieldDecorator('categoryId', {
                                rules: [{
                                    required: true, message: '必须选择商品类别',
                                }],
                                initialValue: defaultData.categoryId  ?
                                    [ ...(defaultData.parentCategoryId === '0' ? [] : [defaultData.parentCategoryId]) ,
                                        defaultData.categoryId] : []
                            })(
                                <Cascader placeholder="请输选择商品类别" options={categoryList} disabled={disabled} />
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <FormItem
                    {...formItemLayout}
                    label="商品名称"
                    >
                    {getFieldDecorator('goodsName', {
                        rules: [{
                            required: true, message: '必须填写商品名称',
                        }, {
                            max: 20, message: '最大长度不超过20'
                        }],
                        initialValue: defaultData.goodsName || ''
                    })(
                        <Input placeholder="请输入商品名称" disabled={disabled}/>
                    )}
                </FormItem>
                <Row>
                    <Col span={12}>
                        <FormItem
                            {...formItemLayoutInline2}
                            label="英文名称"
                            >
                            {getFieldDecorator('goodsEnName', {
                                rules: [{
                                    required: true, message: '必须填写商品英文名称', whitespace: true
                                }, {
                                    max: 30, message: '最大长度不超过30'
                                }],
                                initialValue: defaultData.goodsEnName || ''
                            })(
                                <Input placeholder="请输入商品英文名称" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem
                            {...formItemLayoutInline2}
                            label="商品条码"
                            >
                            {getFieldDecorator('barcode', {
                                rules: [{
                                    required: true, message: '必须填写商品编码',
                                }, {
                                    max: 16, message: '最大长度不超过16'
                                }],
                                initialValue: defaultData.barcode || ''
                            })(
                                <Input placeholder="请输入商品编码" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormItem
                            label="销售规格"
                            required={true}
                            {...formItemLayoutInline2}
                            >
                            <Col span={11}>
                                <FormItem>
                                    {getFieldDecorator('spec', {
                                        rules: [{
                                            required: true, message: '必须填写商品规格'
                                        }, {
                                            max: 6, message: '最大长度不超过6'
                                        }],
                                        initialValue: defaultData.spec || ''
                                    })(
                                        <Input placeholder="请输入商品规格" disabled={disabled}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{textAlign: 'center', fontSize: '16px'}}>/</Col>
                            <Col span={11}>
                                <FormItem>
                                    {getFieldDecorator('unit', {
                                        rules: [{
                                            required: true, message: '必须填写销售单位'
                                        }, {
                                            max: 6, message: '最大长度不超过6'
                                        }],
                                        initialValue: defaultData.unit || ''
                                    })(
                                        <Input placeholder="请输入销售单位" size="large" disabled={disabled}/>
                                    )}
                                </FormItem>
                            </Col>
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                            label="包装数量"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('pkSpec', {
                                rules: [{
                                    required: true, message: '必须填写包装数量'
                                }, {
                                    max: 4, message: '最大长度不超过4'
                                }],
                                initialValue: defaultData.pkSpec !== undefined ? defaultData.pkSpec + '' : ''
                            })(
                                <NumberInput placeholder="请输入包装数量" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                            label="商品属性"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('itemType', {
                                rules: [{ required: true, message: '必须选择商品属性' }],
                                initialValue: defaultData.itemType ? defaultData.itemType + '' : ''
                            })(
                                <Select placeholder="请选择商品属性" disabled={disabled}>
                                    <Option value="1">常温</Option>
                                    <Option value="2">冷藏</Option>
                                    <Option value="3">冷冻</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <FormItem
                            label="长度(cm)"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('length', {
                                rules: [{
                                    required: true, message: '必须填写长度'
                                }, {
                                    max: 4, message: '最大长度不超过4'
                                }],
                                initialValue: defaultData.length !== undefined ? defaultData.length + '' : ''
                            })(
                                <NumberInput placeholder="请输入长度" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                            label="宽度(cm)"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('width', {
                                rules: [{
                                    required: true, message: '必须填写宽度'
                                }, {
                                    max: 4, message: '最大长度不超过4'
                                }],
                                initialValue: defaultData.width !== undefined ? defaultData.width + '' : ''
                            })(
                                <NumberInput placeholder="请输入宽度" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                            label="高度(cm)"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('height', {
                                rules: [{
                                    required: true, message: '必须填写高度'
                                }, {
                                    max: 4, message: '最大长度不超过4'
                                }],
                                initialValue: defaultData.height !== undefined ? defaultData.height + '' : ''
                            })(
                                <NumberInput placeholder="请输入高度" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                            label="商品重量(g)"
                            {...formItemLayoutInline4}
                            >
                            {getFieldDecorator('weight', {
                                rules: [{
                                    required: true, message: '必须填写商品重量'
                                }, {
                                    max: 6, message: '最大长度不超过6'
                                }],
                                initialValue: defaultData.weight !== undefined ? defaultData.weight + '' : ''
                            })(
                                <NumberInput placeholder="请输入商品重量" disabled={disabled}/>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <FormItem
                    {...formItemLayout}
                    label="商品图片"
                    >
                    {getFieldDecorator('image', {
                        rules: [{ required: true, message: '必须上传商品图片' }],
                        initialValue: defaultData.imageKey1 ? [{
                            imageKey1: defaultData.imageKey1,
                            imageKey2: defaultData.imageKey2
                        }] : ''
                    })(
                        <div>
                            <div style={{display: 'flex'}}>
                                <div style={{width: 120}}>
                                    <PhotoUpload limit = { 1 }
                                                 fileSize = { 5000000 }
                                                 data = {{itemcode: defaultData.itemCode}}
                                                 buttonText={'上传'}
                                                 errMessage = { "上传出错! 请重新上传，或稍后上传！" }
                                                 callBack = { this.handlePhotoUpload }
                                                 onRemove = { this.handlePhotoRemove }
                                                 fileList = { this.state.fileList }
                                                 showRemoveIcon = { !disabled }
                                        />
                                    {this.state.fileList.length > 0 ?
                                    <span style={{paddingLeft: 25}}>640*640</span> :null }
                                </div>
                                {this.state.fileList.length > 0 ?
                                <div style={{width: 120}}>
                                    <PhotoUpload limit = { 1 }
                                                 fileSize = { 5000000 }
                                                 fileList = { this.state.fileList2 }
                                                 showRemoveIcon = { false }
                                        />
                                    <span style={{paddingLeft: 25}}>640*450</span>
                                </div> : null}
                            </div>
                            <p>提示：请上传jpg/png格式文件大小不超过5M，建议分辨率不小于640*640</p>
                        </div>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="商品描述"
                    >
                    {getFieldDecorator('memo', {
                        rules: [{ max: 64, message: '商品描述不超过64字', whitespace: true }],
                        initialValue: defaultData.memo || ''
                    })(
                        <Input.TextArea placeholder="请填写商品描述" disabled={disabled}/>
                    )}
                </FormItem>
                <FormItem
                    wrapperCol={{ xs:{ span:24 }, sm:{ span: 19, offset: 3 }}}
                    >
                    <Button onClick={this.handleCancel}>取消并返回</Button>
                    <Button type="primary"
                            htmlType="submit"
                            loading={loading}
                            style={{marginLeft: 10}}>保存并返回</Button>
                </FormItem>
            </Form>
        )
    }
}

export default Form.create()(ItemModifyForm)
